// pages/edit-profile/edit-profile.js
Page({
  data: {
    userInfo: {
      username: '',
      role: '',
      realName: '',
      classes: '',
      phone: '',
      email: ''
    }
  },

  onLoad() {
    this.fetchUserInfo();
  },

  // 获取用户信息
  fetchUserInfo() {
    const username = wx.getStorageSync('username');
    wx.request({
      url: 'http://192.168.172.134:5000/api/user',
      method: 'GET',
      data: { username },
      success: res => {
        if (res.statusCode === 200) {
          this.setData({
            userInfo: res.data
          });
        }
      }
    });
  },

  // 电话输入处理
  onPhoneInput(e) {
    this.setData({
      'userInfo.phone': e.detail.value
    });
  },

  // 邮箱输入处理
  onEmailInput(e) {
    this.setData({
      'userInfo.email': e.detail.value
    });
  },

  // 提交表单
  submitForm() {
    if (!this.validateForm()) return;

    wx.request({
      url: 'http://192.168.172.134:5000/api/updateUser',
      method: 'GET',
      data: this.data.userInfo,
      success: res => {
        if (res.statusCode === 200) {
          wx.showToast({
            title: '修改成功',
            icon: 'success',
            complete: () => {
              setTimeout(() => {
                wx.navigateBack();
              }, 1500);
            }
          });
        }
      }
    });
  },

  // 表单验证
  validateForm() {
    const { phone, email } = this.data.userInfo;

    if (phone && !/^1[3-9]\d{9}$/.test(phone)) {
      wx.showToast({ title: '手机号格式错误', icon: 'none' });
      return false;
    }

    if (email && !/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(email)) {
      wx.showToast({ title: '邮箱格式错误', icon: 'none' });
      return false;
    }

    return true;
  },

  navigateBack() {
    wx.navigateBack();
  }
});